 
#include <string.h>
#include <math.h>
#include "system.h"
#include "f1c100s_de.h"
#include "f1c100s_timer.h"
#include "f1c100s_intc.h"
#include "f1c100s_gpio.h"
#include "f1c100s_pwm.h"
#include "f1c100s_uart.h"
#include "arm32.h"
#include "time0.h"
#include "spi0_flash.h"

int main(void)
{
  system_init();            // Initialize clocks, mmu, cache, uart, ...
  arm32_interrupt_enable(); // Enable interrupts
  timer0_init();
  printf("\r\napp [SPI_FLASH] run. compiled_time %s %s\r\n", __DATE__, __TIME__);
  spi0_flash_init();
  uint32_t flash_id = spi0_flash_read_id();
  printf("flash_id:0x%lX\r\n\r\n", flash_id);

  uint8_t read[1024 * 4 * 4], write[1024 * 4 * 4];
  for (int i = 0; i < 1024 * 4 * 4; i++)
  {
    write[i] = (i * 5) & 0xff;
  }
  uint32_t addr = 0x200000; // 2M
  spi0_flash_erase_sector(addr);
  spi0_flash_erase_sector(addr + 4096);
  spi0_flash_erase_sector(addr + 4096 * 2);
  spi0_flash_erase_sector(addr + 4096 * 3);
  spi0_flash_erase_sector(addr + 4096 * 4);
  spi0_flash_erase_sector(addr + 4096 * 5);

#if 0 // 测试写入
  // spi0_flash_write(addr + 1, write, 255); // 一个page ok
  // spi0_flash_write(addr + 1, write, 255 +  1); // 两个page ok
  spi0_flash_write(addr + 4, write, 256 * 5); // 三个及以上page ok
  // spi0_flash_write(addr, write, 256); // 一个page对齐 ok
  // spi0_flash_write(addr, write, 255); // 一个page对齐 ok
  // spi0_flash_write(addr, write, 256 + 255); // 两个page对齐 OK
  // spi0_flash_write(addr, write, 256 * 3);     // 三个及以上page 对齐 OK
  // spi0_flash_write(addr, write, 256 * 3 + 2); // 三个及以上page 对齐 OK
  spi0_flash_read(addr, read, 1500);
  printf("\r\n********1*************\r\n");
  for (int i = 0; i < 1500; i++)
  {
    printf("%02X ", read[i]);
    if ((i + 1) % 16 == 0)
      printf("\r\n");

    if ((i + 1) % 256 == 0)
      printf("\r\n");
  }
  printf("\r\n********1*************\r\n");
#endif

#if 1
  /*删除测试*/
  spi0_flash_write(addr, write, sizeof(write)); // 三个及以上page ok
  spi0_flash_erase(addr, 5);
  spi0_flash_read(addr, read, sizeof(read));

  for (int i = 0; i < sizeof(read); i++)
  {
    printf("%02X ", read[i]);
    if ((i + 1) % 64 == 0)
      printf("\r\n");

    if ((i + 1) % 4096 == 0)
      printf("\r\n\r\n");
  }
#endif

  while (1)
  {
  }
}
